package cn.uncode.springcloud.starter.security.utils;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import cn.uncode.springcloud.starter.security.auth.EmbedToken;
import cn.uncode.springcloud.starter.security.auth.EmbedUser;
import cn.uncode.springcloud.starter.security.contants.SecurityContant;
import cn.uncode.springcloud.utils.json.JsonUtil;
import cn.uncode.springcloud.utils.net.WebUtil;
import cn.uncode.springcloud.utils.string.StringPool;

/**
 * Secure工具类
 *
 * @author Juny
 */
public class SecureUtil {
    public static final String TOKEN_REQUEST_ATTR = "_TOKEN_REQUEST_ATTR_";
    public static final String USER_REQUEST_ATTR = "_USER_REQUEST_ATTR_";
    public static final String DATAINFO_REQUEST_ATTR = "_DATAINFO_REQUEST_ATTR_";

    /**
     * 获取token信息
     *
     * @return JsonWebToken
     */
    public static EmbedToken getToken() {
        HttpServletRequest request = WebUtil.getRequest();
        // 优先从 request 中获取
        EmbedToken embedToken = (EmbedToken) request.getAttribute(TOKEN_REQUEST_ATTR);
        if (embedToken == null) {
            String auth = request.getHeader(SecurityContant.HEADER);
            if (StringUtils.isNotBlank(auth)) {
                try {
                    Map<String, Object> content = JsonUtil.toMap(auth);
                    embedToken = new EmbedToken(content);
                } catch (Exception ex) {
                    return null;
                }
            }
            if (embedToken != null) {
                // 设置到 request 中
                request.setAttribute(TOKEN_REQUEST_ATTR, embedToken);
            }
        }
        return embedToken;
    }

    /**
     * 获取当前session信息
     *
     * @return session
     */
    public static HttpSession getSession() {
        HttpServletRequest request = WebUtil.getRequest();
        return request.getSession();
    }

    /**
     * 获取用户信息
     *
     * @return EmbedUser
     */
    public static EmbedUser getUser() {
        HttpServletRequest request = WebUtil.getRequest();
        HttpSession session = request.getSession();
        Object user = session.getAttribute(USER_REQUEST_ATTR);
        if (null != user && request.isRequestedSessionIdValid()) {
            return (EmbedUser) user;
        }
        return null;
    }


    /**
     * 获取用户id
     *
     * @return userId
     */
    public static Long getUserId() {
        return (null == getUser()) ? -1 : getUser().getUserId();
    }


    /**
     * 获取用户账号
     *
     * @return userAccount
     */
    public static String getUserAccount() {
        return (null == getUser()) ? StringPool.EMPTY : getUser().getLoginName();
    }


    /**
     * 获取请求头
     *
     * @return header
     */
    public static String getHeader() {
        return WebUtil.getRequest().getHeader(SecurityContant.HEADER);
    }


    public static void main(String[] args) {

    }

}
